//
//  SeekViewController.m
//  WhereToTravel
//
//  Created by dlios on 15/10/20.
//  Copyright © 2015年 zhoushengmin. All rights reserved.
//

#import "SeekViewController.h"
#import "SeekModel.h"
#import "SearchTableViewCell.h"
#import "CountryViewController.h"
#import "CityViewController.h"

@interface SeekViewController ()<UISearchBarDelegate,UITableViewDataSource,UITableViewDelegate>
@property (nonatomic, strong) UISearchBar *searchBar;
@property (nonatomic, strong) UIImageView *notImageView;
@property (nonatomic, strong) UIAlertView *alertView;
@property (nonatomic, strong) UIAlertController *alert;
@property (nonatomic, copy) NSString *searchStr;
@property (nonatomic, strong) NSMutableArray *countryArr;
@property (nonatomic, strong) NSMutableArray *cityArr;
@property (nonatomic, strong) UILabel *notLabel;
@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, assign) NSInteger page;

@end

@implementation SeekViewController

// 视图的出现将tabbar隐藏
- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    self.tabBarController.tabBar.hidden = YES;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(night) name:@"night" object:nil];

    // 左上角返回图标
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"返回"] style:(UIBarButtonItemStylePlain) target:self action:@selector(leftAction:)];
    self.view.backgroundColor = [UIColor whiteColor];
    [self createSearchBar];
    [self createImageView];
    
    // 提示器
    // 判断系统的版本是否大于等于8.0
    if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 8.0) {
        // 提示框
        self.alert = [UIAlertController alertControllerWithTitle:@"温馨提示" message:@"请输入内容" preferredStyle:UIAlertControllerStyleAlert];
        UIAlertAction *action = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleCancel handler:nil];
        [self.alert addAction:action];
    }
    else {
        // 提示框
        self.alertView = [[UIAlertView alloc] initWithTitle:@"温馨提示" message:@"请输入内容" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
    }
}

// 返回
- (void)leftAction:(UIBarButtonItem *)barButton {
    [self.navigationController popViewControllerAnimated:YES];
}

// UISearchBar的创建
- (void)createSearchBar {
    self.searchBar = [[UISearchBar alloc] initWithFrame:CGRectMake(35 * WIDTH, 10 * HEIGHT, WIDTH * 200, 30 * HEIGHT)];
    self.searchBar.placeholder = @"请输入您要搜索的目的地";
    self.navigationItem.titleView = self.searchBar;
    self.searchBar.delegate = self;
    self.searchBar.layer.masksToBounds = YES;
    
}

// 刚进入
- (void)createImageView {
    self.notImageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, WIDTH * 375, HEIGHT * 667)];
    self.notImageView.image = [UIImage imageNamed:@"天空"];
    [self.view addSubview:self.notImageView];
}

// 打入的文字
- (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText {
    self.searchStr = searchText;
    if ([self.searchStr isEqualToString:@""]) {
        [self presentViewController:self.alert animated:YES completion:nil];
        [self.alertView show];
        [self.tableView removeFromSuperview];
        [self.view bringSubviewToFront:self.notImageView];
    }
}
// 点击搜索
- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar {
#pragma mark 数据解析
        NSString *strUrl = [NSString stringWithFormat:@"http://open.qyer.com/qyer/search/index?app_installtime=1435212659&client_id=qyer_ios&client_secret=cd254439208ab658ddf9&count=20&keyword=%@&lat=38.88255829251126&lon=121.5397517042043&page=%ld&place_field=country|city|poi&track_app_channel=AppStore&track_app_version=6.6.6&track_device_info=iPhone5,3&track_deviceid=73524B41-B2E2-47A7-B7FD-F20ADEFBE5DA&track_os= ios&type=place&v=1",self.searchStr,self.page];
        strUrl = [strUrl stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
        NSLog(@"%@",strUrl);
        [ZSMAFNetWork geturl:strUrl body:nil result:ZSMJSON headerFile:nil success:^(id result) {
            
            NSMutableDictionary *strDic = result;
            NSMutableDictionary *secDic = strDic[@"data"];
            NSMutableArray *strArr = secDic[@"entry"];
            self.countryArr = [NSMutableArray array];
            self.cityArr = [NSMutableArray array];
            for (NSMutableDictionary *dic in strArr) {
                SeekModel *destinationModel = [[SeekModel alloc] init];
                [destinationModel setValuesForKeysWithDictionary:dic];
                if ([destinationModel.label isEqualToString:@"国家"]) {
                    [self.countryArr addObject:destinationModel];
                }
                else if ([destinationModel.label isEqualToString:@"城市"]){
                    [self.cityArr addObject:destinationModel];
                }
            }
#pragma mark 判断输入是否存在
            if (self.countryArr.count == 0 && self.cityArr.count == 0) {
                [self createNotView];
            }
            else {
                [self createTableView];
                [self.tableView reloadData];
            }
        } failure:^(NSError *error) {
            NSLog(@"错误是:%@",error);
            
        }];
}

#pragma mark 当没有内容时调用
- (void)createNotView {
    [self.tableView removeFromSuperview];
    self.notLabel = [[UILabel alloc] initWithFrame:CGRectMake(10 * WIDTH, HEIGHT * 200, WIDTH * 355, HEIGHT * 100)];
    self.notLabel.text = @"抱歉,您输入的内容搜索不到,请重新搜索,谢谢";
    self.notLabel.numberOfLines = 0;
    self.notLabel.font = [UIFont boldSystemFontOfSize:22];
    [self.view addSubview:self.notLabel];
    self.notLabel.backgroundColor = [UIColor clearColor];
}

#pragma mark 当有内容时调用
- (void)createTableView {
    self.tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, WIDTH * 375, HEIGHT * 667)];
    self.tableView.dataSource = self;
    self.tableView.delegate = self;
    self.tableView.rowHeight = 100 * HEIGHT;
    [self.view addSubview:self.tableView];
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
}

#pragma mark tableView的数据处理
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 2;
}

-(NSString*)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
{
    if (section == 0) {
        return @"'国家'";
    }
    else {
        return @"'城市'";
    }
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    
    if (section == 0) {
        return self.countryArr.count;
    }
    else {
        return self.cityArr.count;
    }
}

-(UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.section == 0){
        if (self.countryArr.count > indexPath.row) {
            static NSString *reuse = @"reuse";
            SearchTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:reuse];
            if (!cell) {
                cell = [[SearchTableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:reuse];
                cell.backgroundColor = [UIColor clearColor];
                cell.selectionStyle = UITableViewCellSelectionStyleNone;
            }
            SeekModel *destinationModel = self.countryArr[indexPath.row];
            [cell.upImageView sd_setImageWithURL:[NSURL URLWithString:destinationModel.photo] placeholderImage:[UIImage imageNamed:@"占位图"]];
            cell.upLabel.text = destinationModel.cnname;
            cell.mistLabel.text = destinationModel.enname;
            return cell;
        }
    }
    else if (indexPath.section == 1){
        if (self.cityArr.count > indexPath.row) {
             static NSString *otherreuse = @"otherreuse";
             SearchTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:otherreuse];
            if (!cell) {
                cell = [[SearchTableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:otherreuse];
                cell.backgroundColor = [UIColor clearColor];
                cell.selectionStyle = UITableViewCellSelectionStyleNone;
                }
            SeekModel *destinationModel = self.cityArr[indexPath.row];
            [cell.upImageView sd_setImageWithURL:[NSURL URLWithString:destinationModel.photo] placeholderImage:[UIImage imageNamed:@"占位图"]];
            cell.upLabel.text = destinationModel.cnname;
            cell.mistLabel.text = destinationModel.enname;
            cell.downLeftLabel.text = destinationModel.beenstr;
            cell.downRightLabel.text = destinationModel.parentname;
            return cell;
        }
    }
    static NSString *WJMReuse = @"WJMReuse";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:WJMReuse];
    if (!cell) {
        cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:WJMReuse];
    }
    return cell;
}


- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.section == 0) {
        CountryViewController *countryVC = [[CountryViewController alloc] init];
        [self.navigationController pushViewController:countryVC animated:YES];
        SeekModel *destinationModel = self.countryArr[indexPath.row];
        NSString *strId = [NSString stringWithFormat:@"%@",destinationModel.mId];
        countryVC.countryId = strId;
    }
    else if (indexPath.section == 1) {
        CityViewController *cityVC = [[CityViewController alloc] init];
        [self.navigationController pushViewController:cityVC animated:YES];
        SeekModel *destinationModel = self.cityArr[indexPath.row];
        NSString *strId = [NSString stringWithFormat:@"%@",destinationModel.mId];
        cityVC.cityId = strId;
    }
}

- (void)night {
    if ([SingletonNight shareSingletonNight].isSelete == YES) {
        self.tableView.backgroundColor = [UIColor blackColor];
        self.notLabel.textColor = [UIColor whiteColor];
    }
    else {
        self.tableView.backgroundColor = [UIColor whiteColor];
        self.notLabel.textColor = [UIColor blackColor];
    }
}

- (void)dealloc
{
    [[NSNotificationCenter defaultCenter] removeObserver:self name:@"night" object:nil];
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
